package com.ruoyi.chatAi.controller;

import com.ruoyi.chatAi.domain.ChatSession;
import com.ruoyi.chatAi.service.ChatMessageService;
import com.ruoyi.chatAi.service.ChatSessionService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * 聊天会话控制器
 *
 * @author ruoyi
 */
@Anonymous
@RestController
@RequestMapping("/chat")
public class ChatSessionController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ChatSessionController.class);

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 开始新的对话
     */
    @PostMapping(value = "/generate", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter startConversation(@RequestBody ChatSession chatSession) {

        log.info(String.valueOf(chatSession));
        return chatSessionService.generate(chatSession);

    }

    /**
     * 继续现有对话
     */
    @PostMapping(value = "/conversation", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter continueConversation(@RequestBody ChatSession chatSession) {
        return chatSessionService.generateWithSession(chatSession);

    }


    /**
     * 删除会话
     */
    @DeleteMapping("/session/{sessionId}")
    @PreAuthorize("@ss.hasPermi('chatAi:session:remove')")
    public AjaxResult deleteSession(@PathVariable("sessionId") String sessionId) {
        try {
            chatMessageService.deleteChatMessagesBySessionId(sessionId);
            return toAjax(chatSessionService.deleteChatSessionById(sessionId));
        } catch (Exception e) {
            log.error("删除会话失败: ", e);
            return AjaxResult.error("删除会话失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除会话
     */
    @DeleteMapping("/sessions/{sessionIds}")
    @PreAuthorize("@ss.hasPermi('chatAi:session:remove')")
    public AjaxResult deleteSessions(@PathVariable String[] sessionIds) {
        try {
            for (String sessionId : sessionIds) {
                chatMessageService.deleteChatMessagesBySessionId(sessionId);
            }
            return toAjax(chatSessionService.deleteChatSessionByIds(sessionIds));
        } catch (Exception e) {
            log.error("批量删除会话失败: ", e);
            return AjaxResult.error("批量删除会话失败: " + e.getMessage());
        }
    }

    /**
     * 更新会话信息
     */
    @PutMapping("/session")
    @PreAuthorize("@ss.hasPermi('chatAi:session:edit')")
    public AjaxResult updateSession(@RequestBody ChatSession chatSession) {
        try {
            chatSession.setUpdateBy(SecurityUtils.getUsername());
            return toAjax(chatSessionService.updateChatSession(chatSession));
        } catch (Exception e) {
            log.error("更新会话失败: ", e);
            return AjaxResult.error("更新会话失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户的会话列表
     */
    @GetMapping("/sessions/user")
    public AjaxResult getUserSessions() {
        try {
            Long userId = SecurityUtils.getUserId();
            List<ChatSession> sessions = chatSessionService.selectChatSessionsByUserId(userId);
            return AjaxResult.success(sessions);
        } catch (Exception e) {
            log.error("获取用户会话列表失败: ", e);
            return AjaxResult.error("获取用户会话列表失败: " + e.getMessage());
        }
    }

}